<?php

namespace PhpBoot\Controller\Hooks;
use PhpBoot\Controller\ExceptionRenderer;
use PhpBoot\DI\Traits\EnableDIAnnotations;
use PhpBoot\Utils\ZipkinHelper;
use Symfony\Component\HttpFoundation\Request;
use Zipkin\Propagation\Map;
use Zipkin\Timestamp;

/**
 * Class Zipkin
 */
class Zipkin
{
    use EnableDIAnnotations;

    /**
     * Handle an incoming request.
     *
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        $carrier = array_map(function ($header) {
            return $header[0];
        }, $request->headers->all());
        // Extracts the context from the HTTP headers
        $extractedContext = ZipkinHelper::$tracing->getPropagation()->getExtractor(new Map())($carrier);

        ZipkinHelper::$rootSpan = ZipkinHelper::$tracer->nextSpan($extractedContext);
        ZipkinHelper::$rootSpan->start(Timestamp\now());
        ZipkinHelper::$rootSpan->setName($request->getMethod().' '.$request->getPathInfo());
        ZipkinHelper::$rootSpan->setKind('SERVER');

        $response = $next($request);

        ZipkinHelper::$rootSpan->finish();
        ZipkinHelper::$tracer->flush();
        return $response;
    }

    /**
     * @inject
     * @var ExceptionRenderer
     */
    private $exceptionRenderer;
}